# -*- coding: UTF-8 -*-
from flask import Flask,redirect, url_for,flash,jsonify,session
from flask import render_template
from flask import request
import requests
import time
import json
import pymongo
####################################################################
import random
import platform
if(int(platform.python_version()[0])==2):
    from pyecharts import Scatter3D, Bar, Line
    from pyecharts_javascripthon.api import TRANSLATOR
else:
    import pyecharts.options as opts
    from pyecharts.charts import Line
    from pyecharts.faker import Faker
###################################################################

app = Flask(__name__)


#REMOTE_HOST = "https://pyecharts.github.io/assets/js"

def line_chart():
    attr = ["1", "2", "3", "4", "5", "6","7","8","9","10"]
    v1 = [0,0,0,0,0,0,0,0,0,0]
    v2 = [0,0,0,0,0,0,0,0,0,0]
    v3 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    if (int(platform.python_version()[0]) == 2):
        line = Line(width=1000,
            height=600)
        line.add("单位时间A相电压偏差(%)", attr, v1, )
        line.add("单位时间B相电压偏差(%)", attr, v2, )
        line.add("单位时间C相电压偏差(%)", attr, v2, )
        return line
    else:

        line = (
            Line(
                init_opts=opts.InitOpts(
                width=' 1000px',#图表画布宽度
                height=' 600px' ,# 图标画布长度
                )
            )

            .add_xaxis(attr)  # Faker.choose()
            .add_yaxis("单位时间A相电压偏差(%)", v1)
            .add_yaxis("单位时间B相电压偏差(%)", v2)  # , is_smooth=True
            .add_yaxis("单位时间C相电压偏差(%)", v3)
            .set_series_opts(
                label_opts=opts.LabelOpts(is_show=False),
            )
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(
                    axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                    is_scale=False,
                    boundary_gap=False,
                ),
            )

        )

    return line


def num_format_str(data_tmp, bit_len):
    #保留多少小数
    str_tmp = format(data_tmp, "." + str(bit_len) + "f")
    return float(str_tmp)
########################################################################################################


allfrom_flag=""
voltagehistory_flag=""
frequencyhistory_flag=""
harmoniccontent_flag=""
interharmonicratio_flag=""
nobalance_flag=""

@app.route("/")
def home():
    return render_template('home.html')

@app.route("/allfrom")
def allfrom():
    return render_template('all_from.html',value=allfrom_flag)

@app.route("/voltagehistory")
def voltagehistory():
    if (len(voltagehistory_flag) != 12):
        s3d = line_chart()
        return render_template(
            "voltagehistory.html",
            myechart=s3d.render_embed(),
            value=voltagehistory_flag
        )
    else:
        mongo_object_one_one = pymongo.MongoClient('127.0.0.1', 27017, serverSelectionTimeoutMS=10000)
        data_mongo = mongo_object_one_one.dianbiao["log"]
        find_condition = {}
        find_condition["address"] = str(int(voltagehistory_flag))
        find_tmp = data_mongo.find(find_condition).sort("time", -1).limit(10)
        tmp_list2 = [doc for doc in find_tmp]

        data_list_tmpA = []
        data_list_tmpB = []
        data_list_tmpC = []
        for i in tmp_list2:
            data_list_tmpA.append(num_format_str(abs(220 - float(i['voltageA'])) * 100 / 220,2))
            if (i['voltageB'] == "0" and i['voltageC'] == "0"):
                data_list_tmpB.append(0)
                data_list_tmpC.append(0)
            else:
                data_list_tmpB.append(num_format_str(abs(220 - float(i['voltageB'])) * 100 / 220,2))
                data_list_tmpC.append(num_format_str(abs(220 - float(i['voltageC'])) * 100 / 220,2))

        data_list_tmpA.reverse()
        data_list_tmpB.reverse()
        data_list_tmpC.reverse()
        ##########################################
        attr = []
        for i in range(len(tmp_list2)):
            attr.append(str(i + 1))
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)

            line.add("单位时间A相电压偏差(%)", attr, data_list_tmpA, )
            line.add("单位时间B相电压偏差(%)", attr, data_list_tmpB, )
            line.add("单位时间C相电压偏差(%)", attr, data_list_tmpC, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间A相电压偏差(%)", data_list_tmpA)
                .add_yaxis("单位时间B相电压偏差(%)", data_list_tmpB)  # , is_smooth=True
                .add_yaxis("单位时间C相电压偏差(%)", data_list_tmpC)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "voltagehistory.html",
            myechart=line.render_embed(),
            value=voltagehistory_flag
        )

@app.route("/frequencyhistory")
def frequencyhistory():
    if (len(frequencyhistory_flag) != 12):
        attr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        v1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)
            line.add("单位时间频率数据(HZ)", attr, v1, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间频率数据(HZ)", v1)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "frequencyhistory.html",
            myechart=line.render_embed(),
            value=frequencyhistory_flag
        )
    else:
        mongo_object_one_one = pymongo.MongoClient('127.0.0.1', 27017, serverSelectionTimeoutMS=10000)
        data_mongo = mongo_object_one_one.dianbiao["log"]
        find_condition = {}
        find_condition["address"] = str(int(frequencyhistory_flag))
        find_tmp = data_mongo.find(find_condition).sort("time", -1).limit(10)
        tmp_list2 = [doc for doc in find_tmp]


        data_list_tmp=[]
        for i in tmp_list2:
            data_list_tmp.append(num_format_str(float(i['frequency']),2))

        data_list_tmp.reverse()

        ##########################################
        attr = []
        for i in range(len(tmp_list2)):
            attr.append(str(i + 1))
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)

            line.add("单位时间频率数据(HZ)", attr, data_list_tmp, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间频率数据(HZ)", data_list_tmp)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "frequencyhistory.html",
            myechart=line.render_embed(),
            value=frequencyhistory_flag
        )

@app.route("/harmoniccontent")
def harmoniccontent():
    if (len(harmoniccontent_flag) != 12):

        attr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        v1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)

            line.add("单位时间间间谐波含有率数据(%)", attr, v1, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间间间谐波含有率数据(%)", v1)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "harmonic_content.html",
            myechart=line.render_embed(),
            value=harmoniccontent_flag
        )
    else:
        mongo_object_one_one = pymongo.MongoClient('127.0.0.1', 27017, serverSelectionTimeoutMS=10000)
        data_mongo = mongo_object_one_one.dianbiao["log"]
        find_condition = {}
        find_condition["address"] = str(int(harmoniccontent_flag))
        find_tmp = data_mongo.find(find_condition).sort("time", -1).limit(10)
        tmp_list2 = [doc for doc in find_tmp]


        data_list_tmp=[]
        for i in tmp_list2:
            data_list_tmp.append(num_format_str(float(i['harmonic_content']),2))

        data_list_tmp.reverse()
        ##########################################
        attr = []
        for i in range(len(tmp_list2)):
            attr.append(str(i + 1))
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)


            line.add("单位时间间间谐波含有率数据(%)", attr, data_list_tmp, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间间间谐波含有率数据(%)", data_list_tmp)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "harmonic_content.html",
            myechart=line.render_embed(),
            value=harmoniccontent_flag
        )

@app.route("/interharmonicratio")
def interharmonicratio():

    if (len(interharmonicratio_flag) != 12):
        attr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        v1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)

            line.add("单位时间间谐波含有率数据(%)", attr, v1, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间间谐波含有率数据(%)", v1)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "interharmonic_ratio.html",
            myechart=line.render_embed(),
            value=interharmonicratio_flag
        )
    else:
        mongo_object_one_one = pymongo.MongoClient('127.0.0.1', 27017, serverSelectionTimeoutMS=10000)
        data_mongo = mongo_object_one_one.dianbiao["log"]
        find_condition = {}
        find_condition["address"] = str(int(interharmonicratio_flag))
        find_tmp = data_mongo.find(find_condition).sort("time", -1).limit(10)
        tmp_list2 = [doc for doc in find_tmp]


        data_list_tmp=[]
        for i in tmp_list2:
            data_list_tmp.append(num_format_str(float(i['interharmonic_ratio']),2))

        data_list_tmp.reverse()
        ##########################################
        attr = []
        for i in range(len(tmp_list2)):
            attr.append(str(i + 1))
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)


            line.add("单位时间间谐波含有率数据(%)", attr, data_list_tmp, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("单位时间间谐波含有率数据(%)", data_list_tmp)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "interharmonic_ratio.html",
            myechart=line.render_embed(),
            value=interharmonicratio_flag
        )

@app.route("/nobalance")
def nobalance():

    if (len(nobalance_flag) != 12):
        attr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]
        v1 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)

            line.add("三相不平衡数据(%)", attr, v1, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("三相不平衡数据(%)", v1)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "no_balance.html",
            myechart=line.render_embed(),
            value=nobalance_flag
        )
    else:
        mongo_object_one_one = pymongo.MongoClient('127.0.0.1', 27017, serverSelectionTimeoutMS=10000)
        data_mongo = mongo_object_one_one.dianbiao["log"]
        find_condition = {}
        find_condition["address"] = str(int(nobalance_flag))
        find_tmp = data_mongo.find(find_condition).sort("time", -1).limit(10)
        tmp_list2 = [doc for doc in find_tmp]


        data_list_tmp=[]
        for i in tmp_list2:

            if(i['voltageB']=="0" and i['voltageC']=="0"):
                data_list_tmp.append(0)
            else:
                noblance_tmp=(abs(float(i['voltageA']) - float(i['voltageB']))
                              + abs(float(i['voltageB']) - float(i['voltageC']))
                              + abs(float(i['voltageC']) - float(i['voltageA']))) / 3 / 220 * 100

                data_list_tmp.append(num_format_str(noblance_tmp,2))

        data_list_tmp.reverse()
        ##########################################
        attr = []
        for i in range(len(tmp_list2)):
            attr.append(str(i + 1))
        if (int(platform.python_version()[0]) == 2):
            line = Line(width=1000,
                        height=600)

            line.add("三相不平衡数据(%)", attr, data_list_tmp, )
        else:
            line = (
                Line(
                    init_opts=opts.InitOpts(
                        width=' 1000px',  # 图表画布宽度
                        height=' 600px',  # 图标画布长度
                    )
                )

                .add_xaxis(attr)  # Faker.choose()
                .add_yaxis("三相不平衡数据(%)", data_list_tmp)
                .set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False),
                )
                .set_global_opts(
                    xaxis_opts=opts.AxisOpts(
                        axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
                        is_scale=False,
                        boundary_gap=False,
                    ),
                )
            )
        return render_template(
            "no_balance.html",
            myechart=line.render_embed(),
            value=nobalance_flag
        )
##############################################################################################################
@app.route("/allfromPost", methods={'post'})
def allfromPost():
    param = request.form
    global allfrom_flag
    allfrom_flag = param.get("value").strip()
    allfrom_flag=(format(int(allfrom_flag), "0" + str(12) + "d"))
    return redirect("/allfrom")

@app.route("/voltagehistoryPost", methods={'post'})
def voltagehistoryPost():
    param = request.form
    global voltagehistory_flag
    voltagehistory_flag = param.get("value").strip()
    voltagehistory_flag = (format(int(voltagehistory_flag), "0" + str(12) + "d"))
    return redirect("/voltagehistory")

@app.route("/frequencyhistoryPost", methods={'post'})
def frequencyhistoryPost():
    param = request.form
    global frequencyhistory_flag
    frequencyhistory_flag = param.get("value").strip()
    frequencyhistory_flag = (format(int(frequencyhistory_flag), "0" + str(12) + "d"))
    return redirect("/frequencyhistory")

@app.route("/harmoniccontentPost", methods={'post'})
def harmoniccontentPost():
    param = request.form
    global harmoniccontent_flag
    harmoniccontent_flag = param.get("value").strip()
    harmoniccontent_flag = (format(int(harmoniccontent_flag), "0" + str(12) + "d"))
    return redirect("/harmoniccontent")

@app.route("/interharmonicratioPost", methods={'post'})
def interharmonicratioPost():
    param = request.form
    global interharmonicratio_flag
    interharmonicratio_flag = param.get("value").strip()
    interharmonicratio_flag = (format(int(interharmonicratio_flag), "0" + str(12) + "d"))
    return redirect("/interharmonicratio")

@app.route("/nobalancePost", methods={'post'})
def nobalancePost():
    param = request.form
    global nobalance_flag
    nobalance_flag = param.get("value").strip()
    nobalance_flag = (format(int(nobalance_flag), "0" + str(12) + "d"))
    return redirect("/nobalance")

#http://127.0.0.1:5000/configdata
@app.route('/configdata', methods={'GET'})
def Configquery():

    if(len(allfrom_flag)!=12):

        data = {}
        data['number'] = ""

        data['voltageA'] =""
        data['voltageB'] =""
        data['voltageC'] =""
        data['currentA'] =""
        data['currentB'] =""
        data['currentC'] =""

        #data['active'] =1
        #data['reactive'] =1

        data['voltageA_deviation'] =""
        data['max_voltageA_deviation'] =""
        data['voltageA_deviation'] =""
        data['max_voltageA_deviation'] =""
        data['voltageB_deviation'] =""
        data['max_voltageB_deviation'] =""
        data['voltageC_deviation'] =""
        data['max_voltageC_deviation'] =""

        data['voltageA_change'] =""
        data['voltageA_change_num'] =""
        data['voltageB_change'] =""
        data['voltageB_change_num'] =""
        data['voltageC_change'] =""
        data['voltageC_change_num'] =""

        data['interharmonic_ratio'] =""
        data['harmonic_content'] =""
        data['frequency_change'] =""
        data['no_balance'] =""
    else:
        mongo_object_one_one = pymongo.MongoClient('127.0.0.1', 27017, serverSelectionTimeoutMS=10000)
        data_mongo = mongo_object_one_one.dianbiao["tmp"]
        find_condition = {}
        find_condition["address"] = str(int(allfrom_flag))
        find_tmp = data_mongo.find_one(find_condition)
        if(type(find_tmp)==type({})):
            data = {}
            data['number'] = find_tmp["address"]

            data['voltageA'] = num_format_str(float(find_tmp["voltageA"]),2)
            data['voltageB'] = num_format_str(float(find_tmp["voltageB"]),2)
            data['voltageC'] = num_format_str(float(find_tmp["voltageC"]),2)
            data['currentA'] = num_format_str(float(find_tmp["currentA"]),2)
            data['currentB'] = num_format_str(float(find_tmp["currentB"]),2)
            data['currentC'] = num_format_str(float(find_tmp["currentC"]),2)

            # data['active'] =1
            # data['reactive'] =1

            data['voltageA_deviation'] = num_format_str(float(find_tmp["voltageA_deviation"]),2)
            data['max_voltageA_deviation'] = num_format_str(float(find_tmp["max_voltageA_deviation"]),2)
            data['voltageA_deviation'] = num_format_str(float(find_tmp["voltageA_deviation"]),2)
            data['max_voltageA_deviation'] = num_format_str(float(find_tmp["max_voltageA_deviation"]),2)
            data['voltageB_deviation'] = num_format_str(float(find_tmp["voltageB_deviation"]),2)
            data['max_voltageB_deviation'] = num_format_str(float(find_tmp["max_voltageB_deviation"]),2)
            data['voltageC_deviation'] = num_format_str(float(find_tmp["voltageC_deviation"]),2)
            data['max_voltageC_deviation'] = num_format_str(float(find_tmp["max_voltageC_deviation"]),2)

            data['voltageA_change'] = num_format_str(float(find_tmp["voltageA_change"]),2)
            data['voltageA_change_num'] = find_tmp["voltageA_change_num"]
            data['voltageB_change'] = num_format_str(float(find_tmp["voltageB_change"]),2)
            data['voltageB_change_num'] = find_tmp["voltageB_change_num"]
            data['voltageC_change'] = num_format_str(float(find_tmp["voltageC_change"]),2)
            data['voltageC_change_num'] = find_tmp["voltageC_change_num"]

            data['interharmonic_ratio'] = num_format_str(float(find_tmp["interharmonic_ratio"]),2)
            data['harmonic_content'] = num_format_str(float(find_tmp["harmonic_content"]),2)
            data['frequency_change'] = num_format_str(float(find_tmp["frequency_change"]),2)
            data['no_balance'] = num_format_str(float(find_tmp["no_balance"]),2)
        else:
            data = {}
            data['number'] = ""

            data['voltageA'] = ""
            data['voltageB'] = ""
            data['voltageC'] = ""
            data['currentA'] = ""
            data['currentB'] = ""
            data['currentC'] = ""

            # data['active'] =1
            # data['reactive'] =1

            data['voltageA_deviation'] = ""
            data['max_voltageA_deviation'] = ""
            data['voltageA_deviation'] = ""
            data['max_voltageA_deviation'] = ""
            data['voltageB_deviation'] = ""
            data['max_voltageB_deviation'] = ""
            data['voltageC_deviation'] = ""
            data['max_voltageC_deviation'] = ""

            data['voltageA_change'] = ""
            data['voltageA_change_num'] = ""
            data['voltageB_change'] = ""
            data['voltageB_change_num'] = ""
            data['voltageC_change'] = ""
            data['voltageC_change_num'] = ""

            data['interharmonic_ratio'] = ""
            data['harmonic_content'] = ""
            data['frequency_change'] = ""
            data['no_balance'] = ""
    #print (data)
    return jsonify(data)

############################################################################
if __name__ == '__main__':
    app.run("0.0.0.0")#debug = True   "0.0.0.0"